import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'
// import store from '@/store'
// import { getToken } from '@/utils/auth'
import router from '@/router'
import config from '@/config'
// import CryptoJS from 'crypto-js'
// import ipconfig, { keyWord, env } from '@/config/ipConfig'
// import ipconfig, { keyWord } from '@/config/ipConfig'

// create an axios instance
const service = axios.create({
  baseURL: config.baseApi, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  headers: {
    'Content-Type': 'application/json;charset=utf-8'
  },
  timeout: 45000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  (config) => {
    // console.log(JSON.stringify(config))
    // if (store.getters.token) {
    //   config.headers['Web-Token'] = getToken()
    // }
    console.log('config.url', config)
    const configUrl = config.url
    if (
      configUrl.indexOf('gateway') === -1 &&
      configUrl.indexOf('policy-change') === -1 &&
      configUrl.indexOf('policy-contract-synchronization') === -1
    ) {
      // 对请求数据进行AES加密
      // config.data = {
      //   encryption: encryption(JSON.stringify(config.data), keyWord)
      // }
    }

    config.headers['Content-Type'] = 'application/json;charset=utf-8'
    // config.headers['SystemCode'] = ipconfig.SystemCode
    config.headers['EqpCode'] = 'pc'
    config.headers['Token'] = localStorage.getItem('ldtoken') ? localStorage.getItem('ldtoken') : 'eyJhbGciOiJIUzUxMiIsInppcCI6IkdaSVAifQ.H4sIAAAAAAAAAKtWKi5NUrJSSkzJzcxT0lFKrShQsjI0MzQzMTK1NDGvBQApMebnIAAAAA.UG2Qj7F7ASMLBugNG67-wKs0Un6ORrneMkSdio0rKhX0o-fd6BC24T1gCzfVVtsNERPzs4Sjwz8JOyPfLazUSA'
    return config
  },
  (error) => {
    // do something with request error
    console.log('error信息', error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
 
  (response) => {
   
    if (response.request.responseType === 'blob') {
      return response
    } else {
      const res = response.data
      if (response.status !== 200) {
        // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
        if (response.status === 401) {
          // to re-login
          ElMessageBox.alert('登录已超时， 请重新登录', '登录超时', {
            confirmButtonText: '确定',
            type: 'warning',
            showClose: false,
            callback: () => {
              //清理缓存
              router.push(`/login`)
            }
          })
        } else if (response.status === 500) {
          // to re-login
          ElMessageBox.alert('系统错误', '提示', {
            confirmButtonText: '确定',
            type: 'warning',
            showClose: false
          })
        } else if (response.status === 503) {
          // to re-login
          ElMessageBox.alert('网络请求失败', '提示', {
            confirmButtonText: '确定',
            type: 'warning',
            showClose: false
          })
        } else {
          ElMessage.error({
            message: res.msg || '网络请求失败',
            type: 'error',
            duration: 5 * 1000
          })
        }
        return Promise.reject(new Error(res.msg || 'Error'))
      } else {
        console.log(JSON.stringify(res))
       
        return res
      }
    }
  },
  (error) => {
    console.log(error)
    const err = error.response
    console.log('error', JSON.parse(error.config.data))
    //使用自己的错误提示信息 入参需要传入errorMessage
    const data = JSON.parse(error.config.data)
    const errorMessage = error.config && data && data.requestBody && data.requestBody.errorMessage
    if (errorMessage) {
      ElMessage({
        message: errorMessage,
        type: 'warning',
        duration: 5 * 1000
      })
      return Promise.reject()
    }
    if (!err) {
      ElMessage.error({
        message: '网络请求失败',
        type: 'error',
        duration: 5 * 1000
      })
      return Promise.reject()
    }
    if (err.status === 400) {
      ElMessage.error({
        message: '网络请求失败',
        type: 'error',
        duration: 5 * 1000
      })
    } else if (err.status === 401) {
      ElMessageBox.alert('登录已超时， 请重新登录', '登录超时', {
        confirmButtonText: '确定',
        type: 'warning',
        showClose: false,
        callback: () => {
          //清理缓存
          router.push(`/login`)
        }
      })
    } else if (err.status === 500) {
      // to re-login
      ElMessageBox.alert('系统错误', '提示', {
        confirmButtonText: '确定',
        type: 'warning',
        showClose: false
      })
    } else if (err.status === 503) {
      // to re-login
      ElMessageBox.alert('网络请求失败', '提示', {
        confirmButtonText: '确定',
        type: 'warning',
        showClose: false
      })
    } else {
      ElMessage.error({
        message: '网络请求失败',
        type: 'error',
        duration: 5 * 1000
      })
    }
    return Promise.reject(error)
  }
)


export default service
